﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Web.UI;

using CssAndJsCombiner.Configuration;

namespace CssAndJsCombiner.UI.WebControls
{
    public abstract class ClientResourceControl : Control
    {
        public IList<string> Vars { get; private set; }
        public string Group { get; set; }

        private string _path;
        public string Path
        {
            get
            {
                string path = _path;
                if (String.IsNullOrEmpty(path) && !String.IsNullOrEmpty(Group))
                {
                    path = String.Format("~/{0}/{1}", ClientResourceFile, Group);

                    if (Vars.Count > 0)
                    {
                        path += "/" + String.Join("/", Vars.ToArray());
                    }
                }

                return path;
            }

            set { _path = value; }
        }

        protected abstract string ClientResourceFile { get; }

        public ClientResourceControl()
        {
            Vars = new Collection<string>();
        }

        public static string ClientResourcesVersion
        {
            get
            {
                ClientResourcesSection section = ClientResourcesSection.GetSection();
                if (section != null) return section.Version;

                return String.Empty;
            }
        }

        public static string AddVersion(string path, ClientResourceType type)
        {
            string sType = type.ToString().ToLowerInvariant();

            if (path.Contains(sType + ".axd/") && !path.Contains("."+ sType))
            {
                string version = ClientResourcesVersion;
                if (!String.IsNullOrEmpty(version))
                {
                    path += "?" + version;
                }
            }

            return path;
        }
    }
}
